import { Modal } from "@bytedance/mona-ui"
import { get_lid } from "@Utils/getPageDecrypt"
import { store } from "~store"
import { shopLogin, setShopInfo } from "~store/controller/jinritemaiShops"
import { setBuyStatus } from "~store/controller/jinritemaiProduct"
import { setIsInit } from '~store/controller/jinritemaiDecrypt'
import { getShopInfoData } from "@Api/shopsApi"

const baseUrl = import.meta.env.VITE_PLASMO_PUBLIC_BASURL || 'http://doulingyang.cn/'
const proxyUrl = "web/webpagehttp"
let addPushUrl = []
let reqTime = null
let resetlodinnum = 0
let resetlodinmax = 3
let NoAuthorizationTime = null
// let reaoladtimedata = []
const service = (config) => {
  // console.log('config', config)
  let basNewUrl = config.baseUrl
  return new Promise(async (resolve, resject) => {
    if (config.paramete) {
      const { __token = '', msToken = '', inInit = '' } = store.getState().jinritemaiDecrypt

      let { shopuserjwt = '', userShopId = '' } = store.getState().jinritemaiShops
      if (!userShopId && location.hostname === 'fxg.jinritemai.com') {
        if (location.pathname == '/' || location.pathname == '/login/common') {
          return
        }
        const getShopInfoFun = await getShopInfoData()
        // console.log('getShopInfoFun', getShopInfoFun)
        if (!getShopInfoFun.code) {
          userShopId = getShopInfoFun.data.id
          store.dispatch(setShopInfo(getShopInfoFun.data))
        }
      }
      config.paramete.shop_id = config.paramete.shop_id || userShopId || ''
      config.paramete.__token = __token
      config.paramete._bid = config.paramete._bid || "ffa_goods"
      config.paramete._lid = get_lid()
      config.paramete.appid = 1
      config.paramete._ = new Date().getTime()
      config.paramete.msToken = msToken

      const iswebserverapilist = [/\api\/*/, /\dlyadminapi\/*/]
      // console.log('到请求', location.hostname)
      const headers = config.headers || {}
      let getUrlData = {}
      if (iswebserverapilist.filter((item) => item.test(config.url)).length) {
        console.log('config.baseUrl', config.baseURL)
        if (!/\?/.test(config.url)) {
          let str = splitJoint(config.paramete)
          config.url += str
          if (config.method == "GET" || config.method == "get") {
            config.data = undefined
          }
        }
        console.log('configconfig', config)
        getUrlData = {
          url: `${config.baseUrl || baseUrl}${config.url}`,
          method: config.method,
          headers: {
            t: document.cookie,
            ...headers
            // 'Content-Type': 'application/json'
          },
          data: config.data && JSON.stringify(config.data)
        }
        // console.log('getUrlData', config.baseUrl)
      } else {
        getUrlData = {
          url: `${config.baseUrl || baseUrl}${proxyUrl}`,
          method: "post",
          data: JSON.stringify({
            url: config.url,
            method: config.method,
            query: config.paramete,
            data: config.data,
          }),
          headers: {
            t: document.cookie,
            ...headers
          }
        }
      }

      // if (shopuserjwt && shopuserjwt.token) {
      getUrlData.headers.Authorization = `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY3MjlhN2Q0ZTkzM2JlZTVlODQ1MzMzOCIsImlhdCI6MTczMDc4MzMxOCwiZXhwIjoxNzMzMzc1MzE4fQ.KTc7_VsEEiKRcNUS7-BLW9fHoGd0rSFcs3O35HW8wxE`
      // }
      WT_request(getUrlData).then((res) => {
        if (res.readyState === 4 && res.status === 200 && res.responseText) {
          try {
            const getSchearData = JSON.parse(res.responseText)
            if (getSchearData.code === 0) {
              const rex = new RegExp('http://ai.doulingyang.cn/api/task-state*')
              if (rex.test(res.finalUrl)) {
                resolve(getSchearData)
                return
              }
              if (getSchearData.data?.code === 4390) {
                // 用户未授权
                if (NoAuthorizationTime) {
                  clearTimeout(NoAuthorizationTime)
                  NoAuthorizationTime = null
                }
                NoAuthorizationTime = setTimeout(_ => {
                  const poenclu = document.querySelectorAll('[aria-labelledby*="rcDialogTitle"]')
                  if (poenclu && poenclu.length) {
                    poenclu.forEach(elmitem => {
                      elmitem && elmitem.click && elmitem.click()
                    })
                  }
                  store.dispatch(setBuyStatus({
                    status: true,
                    title: getSchearData.data.title,
                    content: getSchearData.data.msg,
                    okText: getSchearData.data.button,
                    url: getSchearData.data.url
                  }))
                  if (inInit) {
                    store.dispatch(setIsInit(false))
                    return
                  }

                  Modal.confirm({
                    title: getSchearData.data.title,
                    content: getSchearData.data.msg,
                    icon: null,
                    okText: getSchearData.data.button,
                    cancelText: " 取消",
                    onOk: () => {
                      open(getSchearData.data.url)
                      return
                    }
                  })
                }, 500)
                resject(false)
                return
              } else if (getSchearData.data?.code === 4388) {
                localStorage.removeItem('wtshopuser')
                location.reload()
                // 用户未购买
                if (NoAuthorizationTime) {
                  clearTimeout(NoAuthorizationTime)
                  NoAuthorizationTime = null
                }
                NoAuthorizationTime = setTimeout(_ => {
                  const poenclu = document.querySelectorAll('[aria-labelledby*="rcDialogTitle"]')
                  if (poenclu && poenclu.length) {
                    poenclu.forEach(elmitem => {
                      elmitem && elmitem.click && elmitem.click()
                    })
                  }
                }, 500)
                resject(false)
                return
              }
              // console.log('getSchearData', getSchearData)
              resolve(getSchearData.data)
            } else {
              if (getSchearData.code === 747) {
                // 前端网页未登录
                addPushUrl.push({ rt: resolve, config: config })
                if (reqTime) {
                  clearTimeout(reqTime)
                  reqTime = null
                }
                reqTime = setTimeout((_) => {
                  clearTimeout(reqTime)
                  reqTime = null
                  // 调用登录
                  resetlodinnum++
                  if (resetlodinnum >= resetlodinmax) {
                    resject("重试失效")
                    addPushUrl = []
                    resetlodinnum = 0
                    return
                  }
                  store.dispatch(
                    shopLogin((jwt) => {
                      if (jwt) {
                        addPushUrl.forEach((resreq) => {
                          setTimeout((_) => {
                            service(resreq.config).then((outserve) => {
                              resreq.rt(outserve)
                            })
                          }, 1)
                        })
                        addPushUrl = []
                        return
                      }
                    })
                  )
                }, 100)
                return
              }
              resject(getSchearData.data || getSchearData)
            }
            return
          } catch (error) {
            resject(res)
            throw new Error("错误")
          }
        }
      })
    }
  })
}
function splitJoint(obj) {
  let arr = []
  for (let key in obj) {
    arr.push(key + "=" + obj[key])
  }
  return arr.length > 0 ? "?" + arr.join("&") : ""
}

export default service
